<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\admin\controller;



use think\facade\Request;
use think\Validate;
use think\Db;

class   Material extends Base
{
    public $mid;
    public $mpInfo;
    public function initialize()
    {


        parent::initialize();
        if(!session('mid')){
            if (input('mid')) {
                $this->mid = input('mid');
                session('mid', $this->mid);
                $this->mpInfo = getMpInfo($this->mid);//缓存公众号信息
                session('mpInfo',$this->mpInfo);
                $mpInfo = Db::name('mp')->where('id','in', $this->role)
                    ->where('is_use','=','1')
                    ->find();
                if ($mpInfo['id'] != $this->mid) {
                    Db::name('mp')->where('id','in',$this->role)
                        ->where('id' ,'=', $this->mid)
                        ->update(['is_use' => '1']);
                    Db::name('mp')->where('id','in', $this->role)
                        ->where('id','neq', $this->mid)
                        ->update(['is_use' => '0']);
                }
            } else {//若没有 Mid 取出默认使用公众号

                $mpInfo = Db::name('mp')->where('id','in', $this->role)
                    ->where('is_use','=', '1')
                    ->find();

                if(!empty($mpInfo)){

                    $this->mid = $mpInfo['id'];
                    session('mid', $this->mid);
                    $this->mpInfo = getMpInfo($this->mid);//缓存公众号信息
                    session('mpInfo',$this->mpInfo);
                }else{
                    $this->error('请先进入公众号','mp/index/mpList');
                }
            }
        }
        $this->mid = session('mid');


    }



    public function addMaterial($type=1){
        $this->assign('type',$type);
        if (Request::isAjax()) {
            $_data = input();
//            $mp = getMpInfo($this->mid);
//            if ($mp['type'] == 1 || $mp['type'] == 3) {
//                ajaxMsg(0, '此功能认证公众号才能使用');
//            }
            $check_repeat = isset($_data['check_repeat']) ? $_data['check_repeat'] : 0;
            $data['mpid'] = $this->mid;
            if($type == 1){
                $validate = new Validate(
                    [
                        'm_image' => 'require',
                    ],
                    [
                        'm_image.require' => '请上传图片',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                ajaxMsg(1, '上传成功');



            }else if($type == 3){
                $validate = new Validate(
                    [
                        'voice_title' => 'require',
                        'm_voice' => 'require',
                    ],
                    [
                        'voice_title.require' => '语音名称不能为空',
                        'm_voice.require' => '请上传语音',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }

                if($check_repeat == 0){
                    $title = $_data['voice_title'];

                    $rs = $this->checkRepeatMaterial($title,'voice');
                    if($rs['percent'] > 75){
                        ajaxMsg(2, '存在相似音乐【'.$rs['title'].'】，是否继续添加');
                    }
                }
                $data = [
                    'mpid' => $this->mid,
                    'title' => $_data['voice_title'],
                    'url' => $_data['m_voice'],

                    'create_time'=>time()
                ];

                $model = new \app\common\model\Material();
                if($model->addMaterial('voice', $data)){
                    ajaxMsg(1, '上传成功');
                }else{
                    ajaxMsg(0, '上传失败');
                }



            }else if($type == 4){
                $validate = new Validate(
                    [
                        'video_title' => 'require',
                        'm_video' => 'require',
                    ],
                    [
                        'video_title.require' => '视频标题不能为空',
                        'm_video.require' => '请上传视频',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }

                if($check_repeat == 0){
                    $title = $_data['video_title'];

                    $rs = $this->checkRepeatMaterial($title,'video');
                    if($rs['percent'] > 70){
                        ajaxMsg(2, '存在相似视频【'.$rs['title'].'】，是否继续添加');
                    }
                }
                $data = [
                    'mpid' => $this->mid,
                    'title' => $_data['video_title'],
                    'content' => $_data['video_content'],
                    'url' => $_data['m_video'],
                    'create_time'=>time()
                ];


                $model = new \app\common\model\Material();

                if($model->addMaterial('video', $data)){
                    ajaxMsg(1, '上传成功');
                }else{
                    ajaxMsg(0, '上传失败');
                }


            }

        } else {
            return view();
        }
    }
    public function editMaterial($id=''){
        if (empty($id) ) {
            $this->error('没有相应的内容');
        }
        $material = Db::name('material')->where(['id' => $id])->find();
        if (!$material || !in_array($material['mpid'],$this->role)) {
            $this->error('修改内容不存在或者与公众号不匹配');
        }
        $type = $material['type'];
        if (Request::isAjax()) {
            $_data = input();

            if($type == 'voice'){
                $validate = new Validate(
                    [
                        'voice_title' => 'require',
                        'm_voice' => 'require',
                    ],
                    [
                        'voice_title.require' => '语音名称不能为空',
                        'm_voice.require' => '请上传语音',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                if($material['from_type'] == 0){
                    $data = [
                        'title' => $_data['voice_title'],
                        'url' => $_data['m_voice'],
                    ];

                    $model = new \app\common\model\Material();
                    $model->updateMaterial(['id'=>$id], $data);
                        ajaxMsg(1, '修改成功');

                }else{
                    ajaxMsg(0, '微信素材不能修改');
                }


            }else if($type == 'video'){
                $validate = new Validate(
                    [
                        'video_title' => 'require',
                        'm_video' => 'require',
                    ],
                    [
                        'video_title.require' => '视频标题不能为空',
                        'm_video.require' => '请上传视频',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                if($material['from_type'] == 0){
                    $data = [
                        'title' => $_data['video_title'],
                        'content' => $_data['video_content'],
                        'url' => $_data['m_video'],
                        'update_time'=>time()
                    ];

                    $model = new \app\common\model\Material();
                    $model->updateMaterial(['id'=>$id], $data);
                        ajaxMsg(1, '修改成功');

                }else{
                    ajaxMsg(0, '微信素材不能修改');
                }

            }

        } else {
            $this->assign('material', $material);
            $this->assign('type', $type);
            return view();
        }
    }
    public function addNews()
    {

        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }

            $model = new \app\common\model\Material();
            $check_repeat = isset($In['check_repeat']) ? $In['check_repeat'] : 0;
            switch ($In['type']) {
                case 1:
                    if(!$model->addMaterial('text', ['content'=>$In['title'],'mpid' => $this->mid])){
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    if($check_repeat == 0){
                        $title = $array[0];
                        $summary = $array[4];
                        $rs = $this->checkRepeatNews($title,'title');
                        if($rs['percent'] > 70){
                            ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                        }else{
                            $rs = $this->checkRepeatNews($summary,'summary');
                            if($rs['percent'] > 75) {
                                ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续添加');
                            }
                        }

                    }

                    $news_data['title'] = $array[0];
                    $news_data['author'] = $array[1];
                    $news_data['thumb_url'] = $array[2];
                    $news_data['show_cover_pic'] = $array[3];
                    $news_data['digest'] = $array[4];
                    $news_data['content'] = $array[5];
                    $news_data['content_source_url'] = $array[6];

                    $data = [
                        'mpid' => $this->mid,
                        'title'=> $news_data['title'],
                        'url'=>$news_data['thumb_url'],
                        'description'=>$news_data['digest'],
                        'create_time'=>time(),
                        'type'=>'news'
                    ];

                    $news_id = $model->addMaterial('news', $data);
                    if($news_id){
                        $news_data['news_id'] = $news_id;
                        $news_data['create_time'] = $data['create_time'];
                        $news_data['mpid'] = $this->mid;
                        Db::name('material_news')->insert($news_data);
                    }

                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];

                    $all_content = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['thumb_url'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        $all_content[] = $news_lists;
                        if($check_repeat == 0){
                            $title = $array[0];
                            $summary = $array[4];
                            $rs = $this->checkRepeatNews($title,'title');
                            if($rs['percent'] > 70){
                                ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                            }else{
                                $rs = $this->checkRepeatNews($summary,'summary');
                                if($rs['percent'] > 75) {
                                    ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续添加');
                                }
                            }
                        }

                    }

                    $data = [
                        'mpid' => $this->mid,
                        'title'=>$all_content[0]['title'],
                        'url'=>$all_content[0]['thumb_url'],
                        'description'=>$all_content[0]['digest'],
                        'create_time'=>time(),
                        'type'=>'news'
                    ];

                    $news_id = $model->addMaterial('news', $data);
                    if($news_id){
                        foreach ($all_content as $news_data) {
                            $news_data['news_id'] = $news_id;
                            $news_data['create_time'] = $data['create_time'];
                            $news_data['mpid'] = $this->mid;
                            Db::name('material_news')->insert($news_data);
                        }
                    }

                    ajaxMsg(1, '操作成功');

                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    if($check_repeat == 0){
                        $title = $array[0];

                        $rs = $this->checkRepeatMaterial($title,'activity');
                        if($rs['percent'] > 75){
                            ajaxMsg(2, '存在相似活动【'.$rs['title'].'】，是否继续添加');
                        }
                    }

                    $data = [
                        'mpid' => $this->mid,
                        'title' => $array[0],
                        'url'=>$array[1],
                        'description'=>$array[2],
                        'link'=>$array[3],
                        'create_time'=>time(),
                        'type'=>'activity',
                    ];

                    if (!$model->addMaterial('activity', $data)) {

                        ajaxMsg(0, '操作失败了');
                    }
                    break;
            }
            ajaxMsg(1, '操作成功');
        } else {
            $data = input();
            $type = isset($data['type']) ? $data['type'] : 0;
            $this->assign('type', $type);
            $this->assign('uploadImg', getHostDomain() . \url('mp/uploadMediaNewsImage'));
            return view('addnews');
        }
    }

    public function editNews($news_id = '')
    {

        if (empty($news_id) ) {
            $this->error('没有相应的内容');
        }
        $material = Db::name('material')->where(['id' => $news_id])->find();
        if (!$material || !in_array($material['mpid'],$this->role)) {
            $this->error('修改内容不存在或者与公众号不匹配');
        }
        $this->mid = $material['mpid'];

        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new \app\common\model\Material();

            $check_repeat = isset($In['check_repeat']) ? $In['check_repeat'] : 0;
            switch ($In['type']) {
                case 1:
                    $model->updateMaterial(['id'=>$news_id], ['content'=>$In['title']]);
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['author'] = $array[1];
                    $news_lists['thumb_url'] = $array[2];
                    $news_lists['show_cover_pic'] = $array[3];
                    $news_lists['digest'] = $array[4];
                    $news_lists['content'] = $array[5];
                    $news_lists['content_source_url'] = $array[6];
                    if($check_repeat == 0){
                        $title = $array[0];
                        $summary = $array[4];
                        $rs = $this->checkRepeatNews($title,'title',$news_id);
                        if($rs['percent'] > 70){
                            ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                        }else{
                            $rs = $this->checkRepeatNews($summary,'summary',$news_id);
                            if($rs['percent'] > 75) {
                                ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续添加');
                            }
                        }

                    }

                    if($material['from_type'] == 0){
                        $news_data = $news_lists;
                    }else{
                        $F = explode(getHostDomain(), $news_lists['thumb_url']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            $result = uploadForeverMedia($filePath, 'image',$this->mid);
                        }else{
                            ajaxMsg('0', '图片不存在');
                        }
                        $article_list[0]['thumb_media_id'] = $result['media_id'];
                        $article_list[0]['author'] = $news_lists['author'];
                        $article_list[0]['title'] = $news_lists['title'];
                        $article_list[0]['content_source_url'] = $news_lists['content_source_url'];
                        $article_list[0]['content'] = $news_lists['content'];
                        $article_list[0]['digest'] = $news_lists['digest'];
                        $article_list[0]['show_cover_pic'] = $news_lists['show_cover_pic'];
                        $news_data = $article_list[0];

                        $news_data['thumb_url'] = $result['url'];
                    }



                    if($material['from_type'] == 1){
                        $wxObj = getWechatActiveObj($this->mid);
                        if (!$wxObj->updateForeverArticles($material['media_id'],$article_list[0],0)) {
                            if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                                ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                            } else {
                                ajaxMsg('0', '未知错误');
                            }

                        }
                    }
                    $data = [
                        'title'=> $news_data['title'],
                        'url'=>$news_data['thumb_url'],
                        'description'=>$news_data['digest'],
                        'update_time'=>time(),

                    ];

                    $model->updateMaterial(['id'=>$news_id], $data);


                    Db::name('material_news')->where('news_id', $news_id)->update($news_data);
                    ajaxMsg(1, '修改成功');


                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];
                    $article_list = array();
                    $all_content = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['thumb_url'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        if($check_repeat == 0){
                            $title = $array[0];
                            $summary = $array[4];
                            $rs = $this->checkRepeatNews($title,'title',$news_id);
                            if($rs['percent'] > 70){
                                ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续编辑');
                            }else{
                                $rs = $this->checkRepeatNews($summary,'summary',$news_id);
                                if($rs['percent'] > 75) {
                                    ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续编辑');
                                }
                            }
                        }

                        if($material['from_type'] == 0){
                            $news_lists['news_id'] = $news_id;
                            $news_lists['mpid'] = $this->mid;
                            $news_lists['create_time'] = time();
                            $all_content[] = $news_lists;
                        }else{
                            $F = explode(getHostDomain(), $news_lists['thumb_url']);
                            if (isset($F['1'])) {
                                $filePath = substr($F['1'], 1);

                                $result = uploadForeverMedia($filePath, 'image',$this->mid);

                            }else{
                                ajaxMsg('0', '图片不存在');
                            }

                            $article_list[$k]['thumb_media_id'] = $result['media_id'];
                            $article_list[$k]['author'] = $news_lists['author'];
                            $article_list[$k]['title'] = $news_lists['title'];
                            $article_list[$k]['content_source_url'] = $news_lists['content_source_url'];
                            $article_list[$k]['content'] = $news_lists['content'];
                            $article_list[$k]['digest'] = $news_lists['digest'];
                            $article_list[$k]['show_cover_pic'] = $news_lists['show_cover_pic'];
                            $news_item = $article_list[$k];
                            $news_item['thumb_url'] = $result['url'];
                            $news_item['news_id'] = $news_id;
                            $news_item['mpid'] = $this->mid;
                            $news_item['create_time'] = time();
                            $all_content[] = $news_item;
                        }


                    }
                    if($material['from_type'] == 1){
                        $wxObj = getWechatActiveObj($this->mid);
                        foreach ($article_list as $k=>$article) {

                            if (!$wxObj->updateForeverArticles($material['media_id'],$article,$k)) {
                                if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                                    ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                                } else {
                                    ajaxMsg('0', '未知错误');
                                }

                            }
                        }
                    }
                    $data = [
                        'title'=> $all_content[0]['title'],
                        'url'=>$all_content[0]['thumb_url'],
                        'description'=>$all_content[0]['digest'],
                        'update_time'=>time(),
                    ];

                    $model->updateMaterial(['id'=>$news_id], $data);

                    Db::name('material_news')->where('news_id', $news_id)->delete();

                    if(Db::name('material_news')->insertAll($all_content)){
                        ajaxMsg(1, '修改成功');
                    }else{
                        ajaxMsg(0, '修改失败');
                    }
                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    $data = [
                        'title' => $array[0],
                        'url'=>$array[1],
                        'description'=>$array[2],
                        'link'=>$array[3],
                        'update_time'=>time()
                    ];
                    if($check_repeat == 0){
                        $title = $array[0];

                        $rs = $this->checkRepeatMaterial($title,'activity',$news_id);
                        if($rs['percent'] > 75){
                            ajaxMsg(2, '存在相似活动【'.$rs['title'].'】，是否继续编辑');
                        }
                    }
                    $model->updateMaterial(['id'=>$news_id], $data);

                    break;
            }
            ajaxMsg(1, '操作成功');

        } else {
            $newsInfo = Db::name('material')->where(['mpid' => $this->mid, 'id' => $news_id])->find();

            $news_type = $newsInfo['type'];

            $type = '';
            switch ($news_type) {
                case 'text':
                    $type = 1;

                    $this->assign('content', $newsInfo['content']);
                    break;
                case 'news':
                    $type = 2;
                    $news_list = Db::name('material_news')->where(['news_id' => $news_id])->select();
                    $news_count = count($news_list);
                    if($news_count>1){
                        $type = 3;
                        $this->assign('info', $news_list);
                    }else{
                        $this->assign('info', $news_list[0]);
                    }

                    break;

                case 'activity':
                    $type = 4;

                    $this->assign('info', $newsInfo);
                    break;
            }
            $this->assign('news_id', $news_id);
            $this->assign('from_type', $newsInfo['from_type']);
            $this->assign('back_url', getHostDomain() . url('index',['type'=>$material['type'],'from_type'=>$material['from_type'] ]));
            $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            $this->assign('type', $type);
            return view('editnews');
        }
    }





    public function index($type = '', $from_type = '')
    {
        $data = input();
        $where = '';
        $keyword = '';
        if(isset($data)){
            if(isset($data['keyword']) && $data['keyword']){
                $keyword = $data['keyword'];
                $where = "(title LIKE '%{$keyword}%' OR title = '{$keyword}' )";
            }

        }

        $this->assign('keyword', $keyword);
        if ($type == '' || $from_type == '') {
            $this->redirect('admin/Material/index', ['type' => 'image', 'from_type' => 0]);
        }
        $model = new \app\common\model\Material();

        $data = $model->getMaterialMpList($type, $this->role, $from_type, 20,$where);
        if ($type == 'news') {
            $news = [];
            $news_ids = [];
            foreach ($data as $key => $val) {

                $news[$val['id']]['id'] = $val['id'];
                $news[$val['id']]['create_time'] = date('Y-m-d H:i',strtotime($val['create_time']));
                $news[$val['id']]['news_item'] = [];
                $news_ids[] = $val['id'];
            }
            $news_list = Db::name('material_news')->where('news_id','in', $news_ids)->select();

            foreach ($news_list as $item) {
                $item['thumb_url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($item['thumb_url']);
                $news[$item['news_id']]['news_item'][] = array(
                    'id'=>$item['id'],
                    'title'=>$item['title'],
                    'content_source_url'=>$item['content_source_url'],
                    'thumb_url'=>$item['thumb_url']
                );
            }
            $this->assign('page', $data->render());
            $this->assign('data', $news);
        } else {
            $this->assign('data', $data);
        }

        $this->assign('type', $type);
        $this->assign('from_type', $from_type);
        return view();
    }

    public function sendRecord()
    {
        $data = Db::name('send_record')->order('id DESC')->paginate(10);
        $news = [];
        $type_list = array(
            'news'=>'图文',
            'image'=>'图片',
            'text'=>'文本'
        );
       $MpList = Db::name('mp')
            ->select();
        foreach ($MpList as $key => $v) {
            $MpList[$v['id']] = $v['name'];
        }

        foreach ($data as $key => $val) {
            $val['create_time'] = date('Y-m-d H:i',$val['create_time']);
            $val['type_name'] = isset($type_list[$val['type']]) ? $type_list[$val['type']] : '其他';
            $val['mp_name'] = isset($MpList[$val['mpid']]) ? $MpList[$val['mpid']] : '其他';
            if($val['from_type'] == 1){
                $val['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($val['url']);
            }else{
                if($val['type'] == 'image'){
                    $val['url'] = getHostDomain() ."/".$val['url'];
                }
            }
            $news[] = $val;
        }
        $this->assign('page', $data->render());

        $this->assign('data', $news);

        return view('sendrecord');
    }



    public function getAdminMaterial($type = '', $from_type = 0)
    {

        $model = new \app\common\model\Material();

        if ($type == 'news') {

            $data = Db::name('material_news')->alias('rmn')
                ->where('rmn.mpid','in',$this->role)->
                join('material', 'material.id = rmn.news_id AND from_type = '.$from_type)->field('rmn.id,rmn.thumb_url,rmn.create_time,rmn.title')->paginate(10);

            if($from_type == 1){
                $data['thumb_url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($data['thumb_url']);
            }

            $this->assign('page', $data->render());
            $this->assign('data', $data);
        } else {

            $data = $model->getMaterialMpList($type, $this->role, $from_type);
            $this->assign('data', $data);
        }
        $this->assign('param', input('param'));
        $this->assign('type', $type);
        $this->assign('from_type', $from_type);

        return view('getadminmaterial');
    }

    function getMaterialNews(){
        $id = Request::post('id');
        $news = Db::name('material_news')->where('id',$id)->find();
        if($news){
            ajaxReturn($news);
        }else{
            ajaxMsg(0, '素材不存在');
        }
    }

    function getMaterialInfo(){

        $id = Request::post('id');
        $type = Request::post('type');
        $from_type = Request::post('from_type');
        if($type == 'text'){
            $material = Db('material')->field('content')->where(['id'=>$id,'type'=>$type])->find();
        }else  if($type == 'image' && $from_type==0){
            $material =  Db::name('picture')->where(['id'=>$id])
                ->where('type',1)
                ->field('mpid,picture as url')
                ->find();
            $material['url']=getHostDomain().DS.$material['url'];
        }else{
            $material = Db('material')->field('title,url')->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();

        }

        if($material){
            ajaxReturn($material);
        }else{
            ajaxMsg(0, '素材不存在');
        }
    }

    function getSendMaterial($type='',$from_type=''){

        if ($type == '' || $from_type == '') {
            $this->redirect('admin/Material/getSendMaterial', ['type' => 'image', 'from_type' => 0]);
        }

        $model = new \app\common\model\Material();

        $data = $model->getMaterialMpList($type, $this->role, $from_type, 12);
        if ($type == 'news') {
            $news = [];
            $news_ids = [];
            foreach ($data as $key => $val) {

                $news[$val['id']]['id'] = $val['id'];
                if($from_type == 1){
                    $val['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($val['url']);
                }
                $news[$val['id']]['url'] = $val['url'];
                $news[$val['id']]['title'] = $val['title'];
                $news[$val['id']]['create_time'] = date('Y-m-d H:i',strtotime($val['create_time']));
                $news[$val['id']]['news_item'] = [];
                $news_ids[] = $val['id'];
            }
            $news_list = Db::name('material_news')->where('news_id','in', $news_ids)->select();

            foreach ($news_list as $item) {
                if($from_type == 1){
                    $item['thumb_url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($item['thumb_url']);
                }

                $news[$item['news_id']]['news_item'][] = array(
                    'title'=>$item['title'],
                    'content_source_url'=>$item['content_source_url'],
                    'thumb_url'=>$item['thumb_url']
                );
            }
            $this->assign('page', $data->render());
            $this->assign('data', $news);
        } else {
            $this->assign('data', $data);
        }

        $this->assign('type', $type);
        $this->assign('from_type', $from_type);
        return view('getsendmaterial');
    }



    public function sendMessage()
    {
        ini_set('max_execution_time', '0');
        if (Request::isAjax()) {
            $in = input();
            $id = isset($in['id']) ? $in['id'] : 0;
            $type = isset($in['type']) ? $in['type'] : '';
            $from_type = isset($in['from_type']) ? $in['from_type'] : 0;

            if($type!="news"&& $type!="image" && $type!="activity"&& $type!="text"){
                ajaxMsg(0, '此类型素材不能群发');
            }
            $model = new \app\common\model\Material();
            if($type == 'image' && $from_type==0){
                $material =  Db::name('picture')->where(['id'=>$id])
                    ->where('type',1)
                    ->field('mpid,picture as url')
                    ->find();
                $material['type'] = 'image';

            }else{
                $material = $model->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();
                if($type == 'news'){
                    $lists = Db::name('material_news')->where('news_id', $id)->select();
                }
            }

            if(!$material){
                ajaxMsg(0, '素材不存在');
            }

            $mpids = Request::post('mp_ids');
            $mpid_arr = array();
            if(strlen($mpids)>0){
                $mpid_arr = explode(',',$mpids);
            }
            if(!$mpid_arr){
                ajaxMsg(0, '请选择公众号');
            }
            $MpList = $this->getRoleMpList();

            $mp_id_list = array();
            foreach ($MpList as $item) {

                $mp_id_list[$item['id']] = $item;
            }

            foreach ($mpid_arr as $item) {
                if(!isset($mp_id_list[$item]) || !$mp_id_list[$item]){
                    ajaxMsg(0, '没有所选公众号权限');
                }
                $mp = $mp_id_list[$item];
                if ($mp['type'] == 1 || $mp['type'] == 3) {
                    ajaxMsg(0, '此功能认证公众号才能使用,【'.$mp['name'].'】不是认证公众号');
                }

            }

            $news_list = array();
            $dow_file_path = '';
            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary', 'admin_id' => $this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content', 'admin_id' => $this->admin_id])->value('value');
            foreach ($mpid_arr as $k=>$item) {

              $mid = $item;
                $news_list[$mid] = array();
                if($type == 'activity' || $type == 'text'){
                  if($type == 'activity' && ($custom_message_summary || $custom_message_content)){
                      $material['description'] .= $custom_message_summary;
                      $material['content'] .= $custom_message_content;
                  }
                    $news_list[$mid] = $material;
                }else if($type=='image'){
                    if(isset($material['mpid']) && $mid == $material['mpid'] && $from_type == 1){
                        $news_list[$mid] = $material['media_id'];
                    }else {
                        if ($from_type == 1) {
                            if (!$dow_file_path) {
                                $F = explode(getHostDomain() . url('mp/Show/image', '', '') . '?url=', $material['url']);
                                if (isset($F['1'])) {
                                    $url = urldecode($F['1']);

                                    if (!empty($Arr = explode('wx_fmt=', $url))) {
                                        $ch = curl_init();
                                        curl_setopt($ch, CURLOPT_URL, $url);
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                                        $file = curl_exec($ch);
                                        curl_close($ch);
                                        $types = array(
                                            'gif' => 'image/gif',
                                            'jpeg' => 'image/jpeg',
                                            'jpg' => 'image/jpeg',
                                            'png' => 'image/png',
                                        );
                                        if (isset($Arr[1]) && key_exists($Arr[1], $types)) {

                                        } else {
                                            $Arr[1] = 'jpg';

                                        }

                                        $file_name = $material['id'].time() . "." . $Arr[1];
                                        $path = \think\facade\Env::get('root_path') . "uploads/wechat/";
                                        $dow_file_path =  "uploads/wechat/".$file_name;
                                        if (!file_exists($path)) mkdir($path, 0777, true);
                                        $resource = fopen($path.$file_name, 'a');
                                        fwrite($resource, $file);
                                        fclose($resource);

                                    }
                                }
                            }
                            if ($result = uploadMedia($dow_file_path, 'image', $mid)) {
                                $news_list[$mid] = $result['media_id'];
                            }

                        } else {
                            if ($result = uploadMedia($material['url'], 'image', $mid)) {
                                $news_list[$mid] = $result['media_id'];
                            }
                        }

                    }

                }else if($type=='news'){
                    if($mid == $material['mpid'] && $from_type == 1 && !$custom_message_summary && !$custom_message_content){
                        $news_list[$mid] = $material['media_id'];
                    }else{
                        if (empty($lists))
                            ajaxMsg('0', '没有内容可上传');

                        $material['description'] .= $custom_message_summary;
                        $material['content'] .= $custom_message_content;
                        if($from_type == 1){

                            foreach ($lists as $key => $val) {
                                $news_image_path = '';
                                if(isset($val['local_url'])){
                                    $news_image_path = $val['local_url'];
                                }else{
                                    $url = $val['thumb_url'];
                                    if (!empty($Arr = explode('wx_fmt=', $url))) {
                                        $ch = curl_init();
                                        curl_setopt($ch, CURLOPT_URL, $url);
                                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
                                        $file = curl_exec($ch);
                                        curl_close($ch);
                                        $types = array(
                                            'gif' => 'image/gif',
                                            'jpeg' => 'image/jpeg',
                                            'jpg' => 'image/jpeg',
                                            'png' => 'image/png',
                                        );
                                        if (isset($Arr[1]) && key_exists($Arr[1], $types)) {

                                        } else {
                                            $Arr[1] = 'jpg';

                                        }
                                        $file_name = time() .$val['id']. "." . $Arr[1];
                                        $path = \think\facade\Env::get('root_path') . "uploads/wechat/";
                                        $news_image_path =  "uploads/wechat/".$file_name;
                                        if (!file_exists($path)) mkdir($path, 0777, true);
                                        $resource = fopen($path.$file_name, 'a');
                                        fwrite($resource, $file);
                                        fclose($resource);

                                        $lists[$key]['local_url'] = $news_image_path;
                                    }
                                }



                                //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                                if ($result = uploadMedia($news_image_path, 'image',$mid)) {
                                    $lists[$key]['thumb_media_id'] = $result['media_id'];
                                    $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                                }

                                $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                                $array[$key]['author'] = $val['author'];
                                $array[$key]['title'] = $val['title'];
                                $array[$key]['content_source_url'] = $val['content_source_url'];
                                $array[$key]['content'] = $val['content'] . $custom_message_content;
                                $array[$key]['digest'] = $val['digest'] . $custom_message_summary;
                                $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                            }
                        }else{
                            foreach ($lists as $key => $val) {
                                $F = explode(getHostDomain(), $val['thumb_url']);
                                if (isset($F['1'])) {
                                    $filePath = substr($F['1'], 1);
                                    //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                                    if ($result = uploadMedia($filePath, 'image',$mid)) {
                                        $lists[$key]['thumb_media_id'] = $result['media_id'];
                                        $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                                    }
                                }
                                $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                                $array[$key]['author'] = $val['author'];
                                $array[$key]['title'] = $val['title'];
                                $array[$key]['content_source_url'] = $val['content_source_url'];
                                $array[$key]['content'] = $val['content'] . $custom_message_content;
                                $array[$key]['digest'] = $val['digest'] . $custom_message_summary;
                                $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                            }

                        }
                        $articleList['articles'] = $array;
                        $wxObj = getWechatActiveObj($mid);
                        if ($result = $wxObj->uploadArticles($articleList)) {
                            $media_id = $result['media_id'];
                            $news_list[$mid] = $media_id;
                        } else {
                            if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                                ajaxMsg(0, '群发失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                            } else {
                                ajaxMsg('0', '未知错误');
                            }
                        }

                    }

                }

            }

            $fails = array();
            $success = array();
            $insert_data = array(
                'type' => isset($material['type']) ? $material['type'] : '',
                'title' => isset($material['title']) ? $material['title'] : '',
                'url' => isset($material['url']) ? $material['url'] : '',
                'description' => isset($material['description']) ? $material['description'] : '',
                'content' => isset($material['content']) ? $material['content'] : '',
                'detail' => isset($material['detail']) ? $material['detail'] : '',
                'link' => isset($material['link']) ? $material['link'] : '',
                'media_id' => isset($material['media_id']) ? $material['media_id'] : '',
                'from_type' => isset($material['from_type']) ? $material['from_type'] : 0,
                'path'=>isset($material['path']) ? $material['path'] : '',
                'create_time' => time(),
            );
            foreach ($news_list as $k=>$item) {

//                $this->SynFriends($k);

                $mp = $mp_id_list[$k];

                if ($type == 'text') {
                    $data = [
                        'text' => [
                            'content' => $item['content'],
                        ],
                        'msgtype' => 'text',
                    ];
                }else if ($type == 'news') {
                    $data = [
                        'msgtype' => 'mpnews',
                        'mpnews' => [
                            'media_id' => $item
                        ]
                    ];
                } else if ($type == 'activity') {
                    $data = [
                        'news' => [
                            'articles' => array(
                                array(
                                    'title'=>$item['title'],
                                    'description'=>$item['description'],
                                    'url'=>$item['link'],
                                    'picurl'=>$item['url'],
                                    //'picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1533038665420&di=dfc1bc453fa24d15dd2140287d8e02a7&imgtype=0&src=http%3A%2F%2Fg.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F79f0f736afc37931ccb794e8e7c4b74542a91117.jpg'
                                )
                            )
                        ],
                        'msgtype' => 'news',
                    ];

                }else if ($type == 'image') {

                    $data = [
                        'msgtype' => 'image',
                        'image' => [
                            'media_id' => $item
                        ]
                    ];
                }

       
                $wxObj = getWechatActiveObj($k);
                $FriendList = Db::name('mp_friends')->where(['mpid' => $k, 'subscribe' => 1,['last_time', '>', time()-(86400*2+1000)]])
                 ->select();

//                $FriendList = Db::name('mp_friends')->where(['mpid' => $k, 'subscribe' => 1])
//                    ->select();
                $status = 0;

                foreach ($FriendList as $friend) {
                    $data['touser'] = $friend['openid'];
                    $result = $wxObj->sendCustomMessage($data);
                    if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
                        $status = 1;
                    } else {
                        if($wxObj->errCode == '45015'){
                            $status = 1;
                        }

                    }
                }


                if($status == 1){
                    $success[] = $mp['name'];

                    $insert_data['mpid'] = $k;

                    Db::name('send_record')->insert($insert_data);
                }else{
                    if(!$FriendList){
                        $fails[] = '公众号【'.$mp['name'].'】群发失败， 错误内容：没有获取到2天内的活跃粉丝';
                    }else{
                        $fails[] = '公众号【'.$mp['name'].'】群发失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg;
                    }

                }



            }

            if(!$fails){
                ajaxMsg(1, '群发成功');
            }else{
                if($success){
                    ajaxMsg(1, '群发成功公众号:'.implode('<br/>',$success).';</br>'.implode('<br/>',$fails));
                }else{
                    ajaxMsg(0, '群发失败,'.implode('<br/>',$fails));
                }

            }

        }



    }

    public function SynFriends($mid)
    {
        $this->mid = $mid;
        $wechatObj = getWechatActiveObj($this->mid);
        $table = config('database.prefix') . 'syn_openid';
        $finish = 1;
        $next_openid =  null;
        $friendTotal = 0;
        $page = 0;
        while ($finish == 1) {
            $opneidTotal = Db::name('syn_openid')->where('mpid', '=', $this->mid)->count('distinct(openid)');
            $sql = "DELETE FROM {$table} WHERE openid IN (SELECT * FROM(SELECT openid FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS b) AND id NOT IN (SELECT * FROM (SELECT MIN(id) FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS c)";
            Db::execute($sql);
            if ($opneidTotal >= $friendTotal && $friendTotal > 0) {
                $synOpenids = Db::name('syn_openid')->where('mpid', '=', $this->mid)
                    ->distinct(true)
                    ->field('openid')
                    ->limit(100 * $page,100)->select();
                if (!empty($synOpenids)) {
                    $openids['user_list'] = [];
                    foreach ($synOpenids as $key => $val) {
                        $openids['user_list'][$key]['openid'] = $val['openid'];
                    }
                    $friends_array = $wechatObj->getUsersInfo($openids);
                    if (isset($friends_array['user_info_list']) && is_array($friends_array['user_info_list'])) {
                        foreach ($friends_array['user_info_list'] as $value) {
                            $value['mpid'] = $this->mid;
                            $value['tagid_list'] = @json_encode($value['tagid_list'], true);
                            if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->field('id')->find()) {
                                Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->update($value);
                            } else {
                                Db::name('mp_friends')->insert($value);
                            }
                        }
                    }
                    $page = $page+1;
                } else {
                    $finish = 2;
                    Db::name('syn_openid')->where('mpid', '=', $this->mid)->delete();
                }

            } else {
                $friendList = $wechatObj->getUserList($next_openid);
                $friendTotal = $friendList['total'];
                if (!empty($friendList) && $friendList['count'] > 0) {
                    $openids = array_chunk($friendList['data']['openid'], 5000);
                    foreach ($openids as $key => $val) {
                        foreach ($val as $key1 => $opneid) {
                            $openid_list[$key][$key1] = [
                                'openid' => $opneid,
                                'mpid' => $this->mid
                            ];
                        }
                        Db::name('syn_openid')->insertAll($openid_list[$key]);
                    }
                    $next_openid = $friendList['next_openid'];

                } else {
                    if ($wechatObj->errCode != '40001' && $wechatObj->errCode != '' && $wechatObj->errMsg != '') {
                        if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                            return $msg;
                        } else {
                            return 'errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg;
                        }
                    }
                    $finish = 2;
                }
            }
        }
        return 1;




    }
    public function delMaterial($id = '', $type = '',$from_type=0)
    {

        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }
        $model = new \app\common\model\Material();
        if($from_type == 0 && $type == 'image'){
            $material = Db::name('picture')->where(['id' => $id])->find();

        }else{
            $material = $model->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();
        }
        if (!$material || !in_array($material['mpid'],$this->role)) {
            ajaxMsg(0, '修改内容不存在或者与公众号不匹配');
        }
        $this->mid = $material['mpid'];

        if($from_type == 1){
            $res = $model->delMaterial($material['media_id'], $this->mid);

        }else{
            if($type == 'image'){
                $res = Db::name('picture')->where(['id' => $id, 'mpid' => $this->mid])->delete();
            }else{
                $res = $model->where(['id' => $id, 'type'=>$type,'mpid' => $this->mid])->delete();
            }
        }
        if ($res){
            if($type=='news'){
                Db::name('material_news')->where(['news_id' => $id])->delete();
            }
            ajaxMsg('1', '删除成功');
        }
        else
            ajaxMsg('0', '删除失败');

    }




    public function uploadMediaNews($id = '', $type = '')
    {
        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }
        $model = new \app\common\model\Material();

        if($type != 'image' ){
            $material = $model->where(['id'=>$id,'type'=>$type])->find();

        }else{
            $material =  Db::name('picture')->where(['id'=>$id])
                ->where('type',1)
                ->field('mpid,picture as url')
                ->find();
            $material['url']=getHostDomain().DS.$material['url'];
        }

        if (!$material || !in_array($material['mpid'],$this->role)) {
            ajaxMsg(0, '修改内容不存在或者与公众号不匹配');

        }
        $this->mid = $material['mpid'];

        $mp = getMpInfo($this->mid);
        if ($mp['type'] == 1 || $mp['type'] == 3) {
            ajaxMsg(0, '此功能认证公众号才能使用');
        }


        if($type == 'image' ){

            if ($result = uploadForeverMedia($material['url'], 'image',$this->mid)) {

                $data['create_time'] = time();
                $data['media_id'] = $result['media_id'];

                $data['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($result['url']);
                if(!empty($result['url'])){

                    $model->addMaterialByMp('image', $data);
                }
                ajaxMsg(1, '上传成功');
            }else{
                ajaxMsg(1, '上传失败');
            }

        }else if($type == 'voice'){

            $F = explode(getHostDomain(), $material['url']);
            if (isset($F['1'])) {
                $filePath = substr($F['1'], 1);

                if ($result = uploadForeverMedia($filePath, 'voice',$this->mid)) {
                    $data = [
                        'mpid' => $this->mid,
                        'title' => $material['title'],
                        'url' => $material['url'],
                        'media_id' => $result['media_id'],
                        'create_time'=>time()
                    ];
                    if(!empty($result['media_id'])){
                        $model->addMaterialByMp('voice', $data);
                    }

                    ajaxMsg(1, '上传成功');
                }
            }else{
                ajaxMsg(0, '上传失败');
            }

        }
        else if($type == 'video'){
            $material = $model->where(['id'=>$id,'type'=>$type])->find();
            $F = explode(getHostDomain(), $material['url']);
                if (isset($F['1'])) {
                    $filePath = substr($F['1'], 1);

                    if ($result = uploadForeverMedia($filePath, 'video',true, ['title' => $material['title'], 'introduction' => $material['content']])) {

                        $data = [
                            'mpid' => $this->mid,
                            'title' => $material['title'],
                            'content' => $material['content'],
                            'url' => $material['url'],
                            'media_id' => $result['media_id'],
                            'create_time'=>time()
                        ];

                        if(!empty($result['media_id'])){
                            $model->addMaterialByMp('video', $data);
                        }
                        ajaxMsg(1, '上传成功');
                    }
                }else{
                    ajaxMsg(0, '上传失败');
                }

        }else if($type == 'news'){
            $lists = Db::name('material_news')->where('news_id', $id)->select();
            if (empty($lists))
                ajaxMsg('0', '没有内容可上传');

//            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary', 'admin_id' => $this->admin_id])->value('value');
//            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content', 'admin_id' => $this->admin_id])->value('value');

            foreach ($lists as $key => $val) {
                $F = explode(getHostDomain(), $val['thumb_url']);
                if (isset($F['1'])) {
                    $filePath = substr($F['1'], 1);

                    if ($result = uploadForeverMedia($filePath, 'image',$this->mid)) {
                        $lists[$key]['thumb_media_id'] = $result['media_id'];
                        $lists[$key]['thumb_url'] = $result['url'];
                        $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                    }
                }
                $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                $array[$key]['author'] = $val['author'];
                $array[$key]['title'] = $val['title'];
                $array[$key]['content_source_url'] = $val['content_source_url'];
                $array[$key]['content'] = $val['content'];
                $array[$key]['digest'] = $val['digest'];
                $array[$key]['show_cover_pic'] = $val['show_cover_pic'];
                $news_item = $array[$key];
                $news_item['thumb_url'] = $lists[$key]['thumb_url'];
                $all_content[] =  $news_item;
            }
            $articleList['articles'] = $array;
            $wxObj = getWechatActiveObj($this->mid);

            if ($result = $wxObj->uploadForeverArticles($articleList)) {
                $data = [
                    'mpid' => $this->mid,
                    'media_id' => $result['media_id'],
                    'create_time'=>time(),
                    'url'=>$all_content[0]['thumb_url'],
                    'title'=>$all_content[0]['title'],
                    'description'=>$all_content[0]['digest'],
                    'type'=>'news'
                ];

                $news_id = $model->addMaterialByMp('news', $data);
                if($news_id){
                    foreach ($all_content as $news_data) {
                        $news_data['news_id'] = $news_id;
                        $news_data['create_time'] = $data['create_time'];
                        $news_data['mpid'] = $this->mid;
                        Db::name('material_news')->insert($news_data);
                    }
                }

                ajaxMsg(1, '上传成功');
            } else {
                if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                    ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                } else {
                    ajaxMsg('0', '未知错误');
                }
            }

        }


    }

    function deleteRecord($id=''){
        Db::name('send_record')->where(['id' => $id])->delete();
    }



    public function groupSend(){

        $MpList = $this->getRoleMpList();

        $this->assign('mpList', $MpList);


        return view('groupsend');
    }

    function str_split_unicode($str, $l = 0,$length=10) {

        if ($l > 0) {

            $ret = array();
            $len = mb_strlen($str, "UTF-8");
            if($len < $length){
                $length = $len;
            }
            for ($i = 0; $i < $length; $i += ($l+1)) {
                $ret[] = mb_substr($str, $i, $l, "UTF-8");
            }
            return $ret;
        }
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }

    function checkRepeatNews($text,$type,$news_id=0){
        if($type == 'title'){
            $where = '0';
            if(strlen($text) > 5){
                $words = $this->str_split_unicode($text,3,15);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }
            if(strlen($text) > 3){
                $words = $this->str_split_unicode($text,2);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }else{
                $where = " title = '{$text}'";
            }

            $news_list = Db::name('material_news')->where('news_id',"<>",$news_id)->where('mpid','in',$this->role)->where($where)->limit(20)->field('title')->select();

            $similar_news = '';
            $percent = 0;
            foreach ($news_list as $item) {
                similar_text($text,$item['title'],$now_percent);
                if($now_percent > $percent){
                    $percent = $now_percent;
                    $similar_news = $item['title'];
                }
            }
            return array(
                'percent'=>$percent,
                'title'=>$similar_news
            );


        }else if($type == 'summary'){
            $where = '0';
            if(strlen($text) > 5){
                $words = $this->str_split_unicode($text,3,15);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR digest like '%{$item}%'";
                    }

                }
            }
            if(strlen($text) > 3){
                $words = $this->str_split_unicode($text,2);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR digest like '%{$item}%'";
                    }

                }
            }else{
                $where = " digest = '{$text}'";
            }

            $news_list = Db::name('material_news')->where('news_id',"<>",$news_id)->where('mpid','in',$this->role)->where($where)->limit(10)->field('title,digest')->select();

            $similar_news = '';
            $percent = 0;
            $digest = '';
            foreach ($news_list as $item) {
                similar_text($text,$item['digest'],$now_percent);
                if($now_percent > $percent){
                    $percent = $now_percent;
                    $similar_news = $item['title'];
                    $digest = $item['digest'];
                }
            }
            return array(
                'percent'=>$percent,
                'title'=>$similar_news,
                'digest'=>$digest,

            );

        }
    }
    function checkRepeatMaterial($text,$type,$id=0){

        $where = '0';
        if(strlen($text) > 5){
            $words = $this->str_split_unicode($text,3,15);
            foreach ($words as $item) {
                if(strlen($item)>1){
                    $where .= " OR title like '%{$item}%'";
                }

            }
        }
        if(strlen($text) > 3){
            $words = $this->str_split_unicode($text,2);
            foreach ($words as $item) {
                if(strlen($item)>1){
                    $where .= " OR title like '%{$item}%'";
                }

            }
        }else{
            $where = " title = '{$text}'";
        }

        $news_list = Db::name('material')->where('id','<>',$id)->where('mpid','in',$this->role)->where(['type'=>$type])->where($where)->limit(20)->field('title')->select();

        $similar_news = '';
        $percent = 0;
        foreach ($news_list as $item) {
            similar_text($text,$item['title'],$now_percent);
            if($now_percent > $percent){
                $percent = $now_percent;
                $similar_news = $item['title'];
            }
        }
        return array(
            'percent'=>$percent,
            'title'=>$similar_news
        );


    }

}